using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 自定义模型管理服务
    /// </summary>
    public class CustomModelService
    {
        private readonly ILogger<CustomModelService> _logger;
        private readonly string _configPath;
        private CustomModelConfig _config;

        public CustomModelService(ILogger<CustomModelService> logger)
        {
            _logger = logger;
            _configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "custom_models.json");
            _config = new CustomModelConfig();
        }

        /// <summary>
        /// 加载自定义模型配置
        /// </summary>
        public async Task LoadConfigAsync()
        {
            try
            {
                if (File.Exists(_configPath))
                {
                    var json = await File.ReadAllTextAsync(_configPath);
                    _config = JsonSerializer.Deserialize<CustomModelConfig>(json) ?? new CustomModelConfig();
                    _logger.LogInformation($"加载自定义模型配置成功，共 {_config.GetTotalModelCount()} 个模型");
                }
                else
                {
                    _config = new CustomModelConfig();
                    await SaveConfigAsync();
                    _logger.LogInformation("创建新的自定义模型配置文件");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "加载自定义模型配置失败");
                _config = new CustomModelConfig();
            }
        }

        /// <summary>
        /// 保存自定义模型配置
        /// </summary>
        public async Task SaveConfigAsync()
        {
            try
            {
                var options = new JsonSerializerOptions
                {
                    WriteIndented = true,
                    Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                };

                var json = JsonSerializer.Serialize(_config, options);
                await File.WriteAllTextAsync(_configPath, json);
                _logger.LogInformation("保存自定义模型配置成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "保存自定义模型配置失败");
            }
        }

        /// <summary>
        /// 添加自定义模型
        /// </summary>
        public async Task<bool> AddCustomModelAsync(string platform, string modelName)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(modelName))
                    return false;

                var models = GetCustomModels(platform);
                if (!models.Contains(modelName))
                {
                    models.Add(modelName);
                    await SaveConfigAsync();
                    _logger.LogInformation($"添加自定义模型: {platform} - {modelName}");
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"添加自定义模型失败: {platform} - {modelName}");
                return false;
            }
        }

        /// <summary>
        /// 移除自定义模型
        /// </summary>
        public async Task<bool> RemoveCustomModelAsync(string platform, string modelName)
        {
            try
            {
                var models = GetCustomModels(platform);
                if (models.Remove(modelName))
                {
                    await SaveConfigAsync();
                    _logger.LogInformation($"移除自定义模型: {platform} - {modelName}");
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"移除自定义模型失败: {platform} - {modelName}");
                return false;
            }
        }

        /// <summary>
        /// 获取指定平台的自定义模型列表
        /// </summary>
        public List<string> GetCustomModels(string platform)
        {
            return platform.ToLower() switch
            {
                "zhipuai" => _config.ZhipuAIModels,
                "deepseek" => _config.DeepSeekModels,
                "openai" => _config.OpenAIModels,
                "alibaba" => _config.AlibabaModels,
                "rwkv" => _config.RWKVModels,
                _ => new List<string>()
            };
        }

        /// <summary>
        /// 获取所有平台的自定义模型
        /// </summary>
        public Dictionary<string, List<string>> GetAllCustomModels()
        {
            return new Dictionary<string, List<string>>
            {
                { "ZhipuAI", _config.ZhipuAIModels },
                { "DeepSeek", _config.DeepSeekModels },
                { "OpenAI", _config.OpenAIModels },
                { "Alibaba", _config.AlibabaModels },
                { "RWKV", _config.RWKVModels }
            };
        }

        /// <summary>
        /// 清理重复的模型名称
        /// </summary>
        public async Task CleanupDuplicatesAsync()
        {
            try
            {
                bool hasChanges = false;

                // 清理各平台的重复项
                hasChanges |= CleanupList(_config.ZhipuAIModels);
                hasChanges |= CleanupList(_config.DeepSeekModels);
                hasChanges |= CleanupList(_config.OpenAIModels);
                hasChanges |= CleanupList(_config.AlibabaModels);
                hasChanges |= CleanupList(_config.RWKVModels);

                if (hasChanges)
                {
                    await SaveConfigAsync();
                    _logger.LogInformation("清理重复模型名称完成");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "清理重复模型名称失败");
            }
        }

        private bool CleanupList(List<string> list)
        {
            var originalCount = list.Count;
            var distinctItems = list.Distinct().ToList();
            
            if (distinctItems.Count != originalCount)
            {
                list.Clear();
                list.AddRange(distinctItems);
                return true;
            }
            return false;
        }
    }

    /// <summary>
    /// 自定义模型配置
    /// </summary>
    public class CustomModelConfig
    {
        /// <summary>
        /// 智谱AI自定义模型
        /// </summary>
        public List<string> ZhipuAIModels { get; set; } = new();

        /// <summary>
        /// DeepSeek自定义模型
        /// </summary>
        public List<string> DeepSeekModels { get; set; } = new();

        /// <summary>
        /// OpenAI自定义模型
        /// </summary>
        public List<string> OpenAIModels { get; set; } = new();

        /// <summary>
        /// 阿里模型自定义模型
        /// </summary>
        public List<string> AlibabaModels { get; set; } = new();

        /// <summary>
        /// RWKV自定义模型
        /// </summary>
        public List<string> RWKVModels { get; set; } = new();

        /// <summary>
        /// 获取总模型数量
        /// </summary>
        public int GetTotalModelCount()
        {
            return ZhipuAIModels.Count + DeepSeekModels.Count + OpenAIModels.Count + 
                   AlibabaModels.Count + RWKVModels.Count;
        }
    }
}
